package middleware

import (
	"server/utils"

	"github.com/gin-gonic/gin"
)

// 错误处理的结构体
type Error struct {
	StatusCode int    `json:"-"`
	Msg        string `json:"msg"`
}

var (
	Success     = NewError(200, "success")
	ServerError = NewError(500, "系统异常，请稍后重试!")
	NotFound    = NewError(404, "Not Found")
)

func OtherError(message string) *Error {
	return NewError(500, message)
}

func (e *Error) Error() string {
	return e.Msg
}

func NewError(statusCode int, msg string) *Error {
	return &Error{
		StatusCode: statusCode,
		Msg:        msg,
	}
}

// 404处理
func HandleNotFound(c *gin.Context) {
	err := NotFound
	c.JSON(
		err.StatusCode,
		utils.DealResponse(utils.Response{
			"code": err.StatusCode,
			"msg":  err.Msg,
		}),
	)
}

func ErrHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()
		if length := len(c.Errors); length > 0 {
			e := c.Errors[length-1]
			err := e.Err
			if err != nil {
				var Err *Error
				if e, ok := err.(*Error); ok {
					Err = e
				} else if e, ok := err.(error); ok {
					Err = OtherError(e.Error())
				} else {
					Err = ServerError
				}
				// 记录一个错误的日志
				c.JSON(
					Err.StatusCode,
					utils.DealResponse(utils.Response{
						"code": Err.StatusCode,
						"msg":  Err.Msg,
					}),
				)
				return
			}
		}

	}
}
